package com.zyh.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @Author zyh
 * @Date 2024/8/13 14:32
 * @Description java对象或者集合转JSON
 */

public class JSONDemo2 {
    public static void main(String[] args) {
        //1.将java对象user转为json格式字符串
        User user = new User("zyh", 20, new Date());
        String userStr = JSON.toJSONString(user);
        System.out.println("userStr = " + userStr);
        //2.将java对象user转为json格式的对象
        JSONObject jsonObj = (JSONObject) JSON.toJSON(user);
        Set<String> keySet = jsonObj.keySet();
        for (String key : keySet) {
            Object value = jsonObj.get(key);
            System.out.println(key + "--" + value);//{"age":20,"birthday":1723534942526,"name":"zyh"}
        }
        System.out.println("---------------------------");
        String name = jsonObj.getString("name");
        Integer age = jsonObj.getInteger("age");
        Date birthday = jsonObj.getDate("birthday");
        String birthdayStr = new SimpleDateFormat("yyyy-MM-dd").format(birthday);
        System.out.println(name + "-" + age + "-" + birthdayStr);//zyh-20-2024-08-13


        //1.将java数组转为json格式字符串
        List<User> list = new ArrayList<>();
        list.add(new User("zyh", 20, new Date()));
        list.add(new User("cxk", 22, new Date()));
        list.add(new User("dz", 24, new Date()));
        String listStr = JSON.toJSONString(list);
        System.out.println("listStr = " + listStr);//[{"age":20,"birthday":1723534942676,"name":"zyh"},{"age":22,"birthday":1723534942676,"name":"cxk"},{"age":24,"birthday":1723534942676,"name":"dz"}]
        //2.将java数组转为json格式对象
        JSONArray jsonList = (JSONArray) JSON.toJSON(list);
        for (Object keys : jsonList) {
            JSONObject jsonObject = (JSONObject) keys;
            String name1 = jsonObject.getString("name");
            Integer age1 = jsonObject.getInteger("age");
            Date birthday1 = jsonObject.getDate("birthday");
            System.out.println(name1 + "-" + age1 + "-" + birthday1);
        }
    }
}
